package com.frejoys.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.frejoys.common.jsonserializer.BigDecimalSerializer;
import com.frejoys.common.jsonserializer.BigNumberSerializer;
import com.frejoys.common.jsonserializer.CustomBeanSerializerModifier;
import com.frejoys.common.jsonserializer.CustomNullJsonSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.math.BigDecimal;
import java.math.BigInteger;

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    @ConditionalOnProperty(name = "null-to-object",prefix = "jackson.config", havingValue = "true")
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        /** 为objectMapper注册一个带有SerializerModifier的Factory */
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
                .withSerializerModifier(new CustomBeanSerializerModifier()));

        SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
        serializerProvider.setNullValueSerializer(new CustomNullJsonSerializer
                .NullObjectJsonSerializer());

        return objectMapper;
    }

    @Bean
    @ConditionalOnMissingBean(Jackson2ObjectMapperBuilderCustomizer.class)
    @ConditionalOnProperty(name = "big-long-to-string",prefix = "jackson.config", havingValue = "true")
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            //将Long类型转换成string类型返回，避免大整数导致前端精度丢失的问题
            builder.serializerByType(Long.TYPE, BigNumberSerializer.instance);
            builder.serializerByType(Long.class, BigNumberSerializer.instance);
            builder.serializerByType(BigInteger.class, BigNumberSerializer.instance);
            // builder.serializerByType(BigDecimal.class, ToStringSerializer.instance);
            builder.serializerByType(BigDecimal.class, BigDecimalSerializer.instance);
        };
    }

}
